package ui.swing.action;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

import ui.swing.Console;

public class ActionPanel extends JPanel {

	public ActionPanel() {
		setLayout(new BorderLayout());
		// define actions
		Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.YELLOW);
		Action greenAction = new ColorAction("Green", new ImageIcon("green-ball.gif"), Color.GREEN);
		Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
		
		// add buttons for these actions
		JPanel pnl = new JPanel();
		pnl.add(new JButton(yellowAction));
		pnl.add(new JButton(greenAction));
		pnl.add(new JButton(redAction));
		add(pnl, BorderLayout.NORTH);
		
		// bottom label
		add(new JLabel("试试Ctrl+Y/G/R"), BorderLayout.SOUTH);
		
		// associate the Y, B, and R keys with names
		InputMap imap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
		imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
		imap.put(KeyStroke.getKeyStroke("ctrl G"), "panel.green");
		imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK), "panel.red");
		
		// associate the names with actions
		ActionMap amap = getActionMap();
		amap = getActionMap();
		amap.put("panel.yellow", yellowAction);
		amap.put("panel.green", greenAction);
		amap.put("panel.red", redAction);
	}
	
	class ColorAction extends AbstractAction {
		
		public ColorAction(String name, Icon icon, Color c) {
			putValue(Action.NAME, name);
			putValue(Action.SMALL_ICON, icon);
			putValue("color", c);
			putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
		}

		public void actionPerformed(ActionEvent e) {
			Color c = (Color)getValue("color");
			setBackground(c);
		}
	}
	
	public static void main(String[] args) {
		Console.run(new ActionPanel(), 300, 300);
	}
}
